<template>
  <div class="page_main">
    <div class="search_box">
      <el-form ref="searchForm" :inline="true" :model="searchForm" size="mini">
        <search-form-box>
          <template slot="showSearch">
            <el-form-item label="项目" prop="customer_id">
              <el-select v-model="searchForm.customer_id" filterable clearable placeholder="请选择项目">
                <el-option v-for="item in customerArr" :key="item.id" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
            <el-form-item label="合同编号" prop="contract_num">
              <el-input v-model="searchForm.contract_num" clearable placeholder="请输入合同编号">
              </el-input>
            </el-form-item>
            <!--            <el-form-item label="审核状态" prop="flow_status">-->
            <!--              <el-select v-model="searchForm.flow_status" clearable placeholder="请选择审核状态">-->
            <!--                <el-option value="3" label="流程中"></el-option>-->
            <!--                <el-option value="4" label="已通过"></el-option>-->
            <!--                <el-option value="2" label="被退回"></el-option>-->
            <!--                <el-option value="0" label="未提交"></el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
          </template>
          <template slot="hideSearch">
            <el-row>
              <el-form-item label="执行开始时间" prop="latest_up_date_start">
                <el-date-picker v-model="searchForm.latest_up_date_start" type="date" value-format="yyyy-MM-dd"
                                format="yyyy年MM月dd日" placeholder="请选择开始时间"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="至" prop="latest_up_date_end">
                <el-date-picker v-model="searchForm.latest_up_date_end" type="date" value-format="yyyy-MM-dd"
                                format="yyyy年MM月dd日" placeholder="请选择结束时间"
                >
                </el-date-picker>
              </el-form-item>

              <el-form-item label="执行结束时间" prop="latest_down_date_start">
                <el-date-picker v-model="searchForm.latest_down_date_start" type="date" value-format="yyyy-MM-dd"
                                format="yyyy年MM月dd日" placeholder="请选择开始时间"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="至" prop="latest_down_date_end">
                <el-date-picker v-model="searchForm.latest_down_date_end" type="date" value-format="yyyy-MM-dd"
                                format="yyyy年MM月dd日" placeholder="请选择结束时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
          </template>
          <template slot="searchBtn">
            <el-form-item>
              <el-button type="primary" plain @click="search">搜索</el-button>
              <el-button type="info" plain @click="resetForm('searchForm')">重置</el-button>
            </el-form-item>
          </template>
        </search-form-box>
      </el-form>
    </div>
    <el-button type="primary" size="mini" v-permission="'add_market_order'" @click="saleTypeDialogVisible = true">新建市场单
    </el-button>
    <el-button type="primary" size="mini" @click="generate">生成链接</el-button>
    <div class="data_box">
      <el-table v-loading="tableLoading" :data="tableData" size="mini" stripe border
                @select="handleSelectionChange" @select-all="selectAll" ref="table"
                :max-height="tableMaxHeight"
      >
        <el-table-column type="selection" :selectable="selectableFunc" width="55">
        </el-table-column>
        <el-table-column label="序号" fixed="left" width="50" align="center">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同编号" prop="contract_num" fixed="left" width="200" show-overflow-tooltip
                         align="center"
        ></el-table-column>
        <el-table-column label="项目" prop="customer_name" fixed="left" width="200" align="center">
        </el-table-column>
        <el-table-column label="时间段" width="200" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" type="primary">
              {{ scope.row.daterange_start + '~' + scope.row.daterange_end }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="换画类型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type === 1" type="primary" size="mini">否</el-tag>
            <el-tag v-else type="success" size="mini">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="设计稿" width="400" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.imgArr.length">
              <el-image v-for="(item,index) in scope.row.imgArr"
                        :key="index"
                        style="width: 100px; height:auto;margin: 5px"
                        :src="item" :preview-src-list="scope.row.imgArr"
              ></el-image>
            </template>
            <div v-else>暂无设计稿</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="!scope.row.generate_link" size="mini" type="info">未生成</el-tag>
            <el-tag v-else-if="scope.row.generate_link && scope.row.confirm_sign_img" size="mini" type="success">已确认
            </el-tag>
            <el-tag v-else-if="scope.row.generate_link" size="mini" type="primary">已生成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="所属子公司" prop="dept_name" width="200" align="center">
        </el-table-column>
        <el-table-column label="提交日期" min-width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.created_at ? scope.row.created_at.substring(0, 10) : '' }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="申请人" prop="user" width="120" align="center">-->
        <!--        </el-table-column>-->
        <el-table-column label="备注" prop="memo" min-width="300" align="center">
        </el-table-column>
        <el-table-column label="审核状态" fixed="right" width="80" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.flow_status === 3" size="mini" type="primary">流程中</el-tag>
            <el-tag v-if="scope.row.flow_status === 4" size="mini" type="success">已通过</el-tag>
            <el-tag v-if="scope.row.flow_status === 2" size="mini" type="danger">被退回</el-tag>
            <el-tag v-if="scope.row.flow_status === 0" size="mini" type="info">草稿箱</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240" align="center">
          <template slot-scope="scope">
            <el-button-group>
              <el-button type="primary" size="mini" v-permission="'look_market_order'" @click="look(scope.row.id)">查看
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="searchForm.page"
      :page-sizes="[10,20,50,100, 200, 400]"
      :page-size.sync="searchForm.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!--    <el-dialog title="设计稿" center :visible.sync="dialogVisible" width="60%" @close="dialogClose">-->
    <!--      <el-card>-->
    <!--        <div slot="header" class="clearfix">-->
    <!--          <el-upload-->
    <!--            action="https://jsonplaceholder.typicode.com/posts/"-->
    <!--            :on-preview="handlePreview"-->
    <!--            :show-file-list="false"-->
    <!--            :before-upload="beforeUpload"-->
    <!--          >-->
    <!--            <el-button size="mini" type="primary">点击上传</el-button>-->
    <!--          </el-upload>-->
    <!--        </div>-->
    <!--        <div v-show="tmpRow.dialogImgUrlArr.length>0" class="flex flex-grow justify-start">-->
    <!--          <el-card style="margin: 5px" v-for="(src,index) in  tmpRow.dialogImgUrlArr" :key="index">-->
    <!--            <el-card shadow="always">-->
    <!--              <el-image style="width: 200px;height: auto" :src="src" :preview-src-list="tmpRow.dialogImgUrlArr"-->
    <!--              ></el-image>-->
    <!--            </el-card>-->
    <!--            <div style="text-align: center;margin-top: 10px">-->
    <!--              <el-button type="danger" size="mini" @click="tmpRow.dialogImgUrlArr.splice(index,1)">删除</el-button>-->
    <!--            </div>-->
    <!--          </el-card>-->
    <!--        </div>-->
    <!--        <div v-show="tmpRow.dialogImgUrlArr.length===0" style="text-align: center">-->
    <!--          暂无图片-->
    <!--        </div>-->
    <!--      </el-card>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>-->
    <!--        <el-button size="mini" type="primary" @click="dialogVisible = false">保 存</el-button>-->
    <!--      </span>-->
    <!--    </el-dialog>-->
    <el-dialog title="市场单类型" :visible.sync="saleTypeDialogVisible" width="300px" center
               @close="closeSaleTypeDialog"
    >
      <el-form size="mini" style="width: 260px;margin: 0 auto">
        <el-form-item label="类型">
          <el-radio-group v-model="type">
            <el-radio :label="1">普通</el-radio>
            <el-radio :label="2">换画</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="saleTypeDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="toCreateMarketOrderPage">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SearchFormBox from '@/components/SearchFormBox'
import { cloneDeep } from 'lodash'
import { company_list_all } from '@/api/customer/customer'
import { generateUUID } from '@/utils/util'
import { generate_confirm_bill, list } from '@/api/merketOrder'

export default {
  name: 'marketOrderList',
  components: {
    SearchFormBox
  },
  data() {
    return {
      tableMaxHeight: 0,
      searchForm: {
        page: 1,
        page_size: 10,
        type: 1,
        dept_id: null,
        customer_id: null,
        contract_id: null,
        contract_num: null,
        bill_sale_id: null,
        flow_status: null,
        latest_up_date_start: null,
        latest_up_date_end: null,
        latest_down_date_start: null,
        latest_down_date_end: null
      },
      listParams: {
        page: 1,
        page_size: 10,
        type: 1,
        dept_id: null,
        customer_id: null,
        contract_id: null,
        contract_num: null,
        bill_sale_id: null,
        flow_status: null,
        latest_up_date_start: null,
        latest_up_date_end: null,
        latest_down_date_start: null,
        latest_down_date_end: null
      },
      total: 0,
      tableData: [],
      tableLoading: false,
      dialogVisible: false,
      tmpRow: {
        id: null,
        dialogImgUrlArr: []
      },
      customerArr: [],
      contractArr: [],
      billSaleArr: [],
      selectRows: [],
      selectRowContractNum: '',
      saleTypeDialogVisible: false,
      saleTypeDialogVisible1: false,
      type: 1
    }
  },
  created() {
    this.tableMaxHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 210
    this.getList()
    this.initCustomerArr()
  },
  methods: {
    search() {
      this.searchForm.page = 1
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    getList() {
      this.tableLoading = true
      list(this.listParams).then(res => {
        this.tableLoading = false
        this.tableData = res.data.records
        this.tableData.forEach(item => {
          this.$set(item, 'imgArr', (item.designPicList || []).map(item => {
            return item.pic_url
          }))
        })
        this.total = res.data.total
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    toCreateMarketOrderPage() {
      let uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          is_create: true,
          type: this.type
        }
      })
      this.saleTypeDialogVisible = false
      this.$router.push({
        name: 'create_market_order',
        query: {
          uuid
        }
      })
    },
    handleSelectionChange(val, row) {
      if (this.selectRows.length === 0) {
        this.selectRows = val
        this.selectRowContractNum = row.contract_num
      } else {
        if (row.contract_num === this.selectRowContractNum) {
          this.selectRows = val
        } else {
          this.$message.error('所选择的市场单合同编号与已经选中的市场单的合同编号不一致')
          this.$refs.table.toggleRowSelection(row, false)
        }
      }
    },
    selectableFunc(row) {
      return row.imgArr.length > 0
    },
    dialogClose() {
      this.tmpRow = {
        id: null,
        dialogImgUrlArr: []
      }
    },
    showUploadImg(row) {
      this.tmpRow.id = row.id
      this.tmpRow.dialogImgUrlArr = cloneDeep(row.imgArr)
      this.dialogVisible = true
    },
    initCustomerArr() {
      company_list_all({}).then(res => {
        this.customerArr = res.data
      })
    },
    look(id) {
      let uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          id: id
        }
      })
      this.$router.push({
        name: 'look_market_order_detail',
        query: {
          uuid
        }
      })
    },
    selectAll(flag) {
      if (flag) {
        if (this.selectRowContractNum === '') {
          this.$message.warning('请先选择一个市场单确定所需要的合同编号')
          this.$refs.table.clearSelection()
        }
      } else {
        this.selectRows = []
        this.selectRowContractNum = ''
      }
    },
    generate() {
      if (this.selectRows.length === 0) {
        this.$message.warning('请先选择需要生成的市场单')
        return
      }
      const that = this
      this.$confirm('确定生成?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectRows.map(item => {
          return item.id
        })
        const loading = this.$loading({
          lock: true,
          text: '生成中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        // 生成链接
        generate_confirm_bill({ billMarketIdList: ids }).then(res => {
          this.$message.success('生成成功，稍等将弹出链接')
          this.$refs.table.clearSelection()
          this.selectRows = []
          this.selectRowContractNum = ''
          setTimeout(() => {
            const text = 'https://oa.meilaiwenhua.com/#/customer_check?batchStr=' + res.message
            this.$alert(text, '链接', {
              confirmButtonText: '复制',
              callback: () => {
                that.doCopy(text)
              }
            })
          }, 1000)
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {

      })
    },
    doCopy(text) {
      this.$copyText(text).then((res) => {
        console.log('内容已复制到剪切板！，复制的内容为：' + res.text)
      }).catch(err => {
        this.$message.error('复制失败')
      })
    },
    closeSaleTypeDialog() {
      this.type = 1
    }
  }
}
</script>

<style scoped lang="scss">
.page_main {
  margin-top: 20px;
  padding: 0 20px;
}

.data_box {
  margin-top: 10px;
}

/* 禁用全选 */
/deep/ .el-table__fixed-header-wrapper .el-table-column--selection {
  text-indent: -999999px;
}
</style>
